package com.bingquan.company.filter;

import com.bingquan.company.feign.TokenFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

// todo   為啥這個swagger  會走這個接口
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private TokenFeign tokenFeign;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("enter token filer");
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders httpHeaders = request.getHeaders();
        String token = httpHeaders.getFirst("token");
        //TODO
        String userId = tokenFeign.getUserId(token);
//        String userId = "userId------aaa";
        System.out.println(userId);
        URI uri = request.getURI();
        System.out.println(uri.getPath());
        System.out.println(uri.getHost()+uri.getPort());
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .headers(headers -> headers.add("userId", userId))
                .build();
        ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
        return chain.filter(build).then(Mono.fromRunnable(() ->{
                    URI uri1 = request.getURI();
                    System.out.println(uri1.getPath()+uri1.getHost()+uri1.getPort());
                }
                ));
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
